<script lang="ts">
export default {
  name: 'cmenu'
};
</script>

<script setup lang="ts">
import { MenuQuery, MenuForm } from '@/api/menu/types';
import { MenuTreeVue } from '@/api/user/types';
import {
  listMenus,
  getMenuForm,
  listMenuOptions,
  addMenu,
  deleteMenu,
  updateMenu
} from '@/api/menu';
import { statusOptionList } from '@/option'
import { usePermissionStoreHook } from '@/store/modules/permission';

import { MenuTypeEnum } from '@/enums/MenuTypeEnum';

import SvgIcon from '@/components/SvgIcon/index.vue';
import IconSelect from '@/components/IconSelect/index.vue';

const permissionStore = usePermissionStoreHook();
const queryFormRef = ref(ElForm);
const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false
});

const queryParams = reactive<MenuQuery>({
  name: '',
  url: ''
});
const menuList = ref<MenuTreeVue[]>([]);

const formData = reactive<MenuForm>({
  name: '',
  parentId: 0,
  status: 1,
  orderNum: 1,
  type: MenuTypeEnum.MENU,
  backgroundUrl: '',
  vueComponent: '',
  method: 'post',
  delFlag: -1
});
const stgStr = ref('edit')

const validatePass2 = (rule: any, value: any, callback: any) => {

  callback()
  // if (value === '') {
  //   callback(new Error('Please input the password again'))
  // } else if (value !== formData.pass) {
  //   callback(new Error("Two inputs don't match!"))
  // } else {
  //   callback()
  // }
}
const rules = reactive({
  // parentId: [{ required: true, message: '请选择顶级菜单', trigger: 'blur' }],
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
  // vuePath: [{ required: true, message: '请输入正确路由路径，由26个字母组成 (目录以/开头)', trigger: 'blur', pattern: /^[/][a-zA-Z]*$/ }],
  vueComponent: [
    { required: true, message: '请输入组件完整路径，如：system/user/index || Layout', trigger: 'blur' }
  ],
  // vueComponent: [
  //   { required: true, message: '请输入组件完整路径，如：system/user/index', trigger: 'blur', pattern: /^[a-zA-Z][\w-]*\/[a-zA-Z][\w-]*\/[a-zA-Z][\w-]*$/ }
  // ]
});

// 选择表格的行菜单ID
const selectedRowMenuId = ref<number | undefined>();


/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  listMenus(queryParams)
    .then((res) => {

      menuList.value = permissionStore.generateRoutes(res.data.data);
    })
    .then(() => {
      loading.value = false;
    });
}

/**
 * 查询重置
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**
 * 行点击事件
 *
 * @param row
 */
function onRowClick(row: MenuTreeVue) {


}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function openDialog(row?: MenuTreeVue, stg = 'edit') {
  dialog.visible = true;
  stgStr.value = stg

  if (stg === 'edit') {
    row && Object.assign(formData, row)
    dialog.title = '编辑菜单';
  } else {
    row && Object.assign(formData, { parentId: row.id })
    console.log(formData)
    dialog.title = '新增菜单';
  }

}


/**
 * 菜单提交
 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const menuId = formData.id;
      if (menuId) {
        updateMenu(formData).then(() => {
          ElMessage.success('修改成功');
          closeDialog();
          handleQuery();
        });
      } else {
        addMenu(formData).then(() => {
          ElMessage.success('新增成功');
          closeDialog();
          handleQuery();
        });
      }
    }
  });
}

/**
 * 删除菜单
 */
function handleDelete(menuId: number) {
  if (!menuId) {
    ElMessage.warning('请勾选删除项');
    return false;
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteMenu(menuId).then(() => {
        ElMessage.success('删除成功');
        handleQuery();
      });
    })
    .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.id = undefined
  formData.name = ''
  formData.parentId = 0
  formData.status = 1
  formData.orderNum = 1
  formData.type = MenuTypeEnum.MENU
  formData.backgroundUrl = ''
  formData.url = ''
  formData.vuePath = ''
  formData.vueComponent = ''
  formData.vueIcon = ''
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input v-model="queryParams.name" placeholder="菜单名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="路径" prop="url">
          <el-input v-model="queryParams.url" placeholder="" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><template #icon>
              <i-ep-search />
            </template>搜索</el-button>
          <el-button @click="resetQuery">
            <template #icon>
              <i-ep-refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div> -->

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog(undefined, 'add')">
          <template #icon>
            <i-ep-plus />
          </template>
          新增
        </el-button>
      </template>

      <el-table v-loading="loading" :data="menuList" highlight-current-row
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @row-click="onRowClick" row-key="id" border>
        <el-table-column label="菜单名称" min-width="200">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.type === MenuTypeEnum.BUTTON
              ? 'button'
              : scope.row.vueIcon
              " />
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="菜单类型" align="center" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.type === MenuTypeEnum.CATALOG" type="warning">目录</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.MENU" type="success">菜单</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.BUTTON" type="danger">按钮</el-tag>
            <el-tag v-if="scope.row.type === MenuTypeEnum.EXTLINK" type="info">外链</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限标识" align="center" width="200" prop="perms" />

        <el-table-column label="状态" align="center" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁止</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="100" prop="orderNum" />

        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" link size="small" @click.stop="openDialog(scope.row, 'add')"
              v-if="scope.row.type == 0 || scope.row.type == 1">
              <i-ep-plus />新增
            </el-button>

            <el-button type="primary" link size="small" @click.stop="openDialog(scope.row)">
              <i-ep-edit />编辑
            </el-button>
            <el-button type="primary" link size="small" @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" @close="closeDialog" width="750px">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入菜单名称" />
        </el-form-item>

        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="formData.type">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
            <el-radio :label="3">外链</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="formData.type === 3" label="外链地址" prop="vuePath">
          <el-input v-model="formData.vuePath" placeholder="请输入外链完整路径" />
        </el-form-item>

        <el-form-item label="路由路径" prop="vuePath" v-if="formData.type === 0 || formData.type == 1">
          <el-input v-if="formData.type == 0" v-model="formData.vuePath" placeholder="/system  (目录以/开头)" />
          <el-input v-else v-model="formData.vuePath" placeholder="/user (目录以/开头)" />
        </el-form-item>

        <!-- 组件页面完整路径 -->
        <el-form-item v-if="formData.type == MenuTypeEnum.MENU || formData.type == MenuTypeEnum.CATALOG" label="页面路径"
          prop="vueComponent">
          <el-input v-model="formData.vueComponent" placeholder="system/user/index" style="width: 95%">
            <template v-if="formData.parentId != 0" #prepend>src/views/</template>
            <template v-if="formData.parentId != 0" #append>.vue</template>
          </el-input>
        </el-form-item>

        <!-- 权限标识 -->
        <el-form-item v-if="formData.type == 2" label="权限标识" prop="backgroundUrl">
          <el-input v-model="formData.backgroundUrl" placeholder="sys:user:add" />
        </el-form-item>
        <!-- <el-form-item v-if="formData.type == 2" label="后台地址" prop="backgroundUrl">
          <el-input v-model="formData.backgroundUrl" placeholder="/system/user/index" />
        </el-form-item> -->
        <el-form-item label="图标" prop="vueIcon" v-if="formData.type !== 2">
          <!-- 图标选择器 -->
          <icon-select v-model="formData.vueIcon" />
        </el-form-item>

        <el-form-item label="跳转路由" v-if="formData.type == MenuTypeEnum.CATALOG">
          <el-input v-model="formData.url" placeholder="跳转路由" />
        </el-form-item>

        <el-form-item label="状态" v-if="formData.type !== 2">
          <el-radio-group v-model="formData.status">
            <el-radio v-for="item in statusOptionList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="formData.orderNum" style="width: 100px" controls-position="right" :min="0"
            :precision="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
